/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-23 14:05:56
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-30 17:03:44
 */
import { parse } from '../../../../mapUtils/Geojson2WktUtil';
import { projectLngLatToWebMercator } from '../../../../mapUtils/CoordinateUtil';
import { throttle } from 'throttle-debounce';
import IGridTool from '../IGridTool';
import Prefix from '../../constant/Prefix';

/**
 * 简化电网图层工具箱
 * @implements {IGridTool}
 */
class SimpleGridTool extends IGridTool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.name = 'SimpleGridTool';
    this.desc = '简化电网图层工具箱';
    this.layeridPrefix = Prefix['SimpleGrid'];
    this.defaultSchemaid = 5;
    this._refresh = throttle(this.THROTTLE_DURATION, () => {
      this.refresh();
    }).bind(this);
  }

  /**
     * 刷新简化图层
     * @override
     */
  async refresh() {
    if (this.isLocked()) {
      return;
    }
    // 当前请求时间
    let currentRequestTime = this.latestRequestTime = new Date().getTime();
    // 获取当前缩放等级下配置的图层列表
    var data = await this.getApi().PwghGhsjTxfw.figure.get_figure_getEquitpType(
      {
        params: {
          zoom: this.getTool('BaseMapTool').getZoom(),
          schemaid:
                        this.searchOption.schemaid || this.defaultSchemaid
        }
      }
    );
    // 过期请求不处理
    if (this._isOutDate(currentRequestTime)) {
      return;
    }
    let sbzlxs = data.datas;
    let promiselist = [];
    // 获取范围、缩放等级
    let extent = this.getTool('BaseMapTool').getBounds();
    let shape = parse(
      turf.polygon(
        projectLngLatToWebMercator(
          turf.bboxPolygon(extent).geometry.coordinates
        )
      ).geometry
    );
    let zoom = this.getTool('BaseMapTool').getZoom();
    let schema = this.searchOption.schema || this.getConfig().get('SCHEMA');
    var firstRequest = true;
    // 拼接请求数据
    sbzlxs.forEach(({ sblx, oid }) => {
      this.getApi()
        .PwghGhsjTxfw.sbjhQuery.post_sbjhQuery_showGhdwEquip({
          params: Object.assign({}, this.searchOption, {
            zoom,
            sblx,
            shape,
            oid,
            schema
          })
        })
        .then((res) => {
          // 过期请求不处理
          if(!this._isOutDate(currentRequestTime)) {
            this._showBySgmapLayer(
              [
                {
                  sblx,
                  res
                }
              ],
              firstRequest
            );
          }
          firstRequest = false;
        })
        .catch((err) => {
          console.log('post_figure_showGhdwEquip error : ', err);
        });
    });
    Promise.all(promiselist).then((resList) => {
      // 过期请求不处理
      if(!this._isOutDate(currentRequestTime)) {
        this._showBySgmapLayer(resList);
      }
    });
  }
}

export default SimpleGridTool;
